<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="1000px"
    title="关联配送终端"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="配送商名称">
            <div>{{ serviceDetail.distributeName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送产品信息">
            <div>{{ getProductName(serviceDetail) }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送费">
            <div>
              <div v-if="serviceDetail.computeMode==='固定价格'">
                <span>{{ serviceDetail.distributePrice }}元</span>
                <span v-if="serviceDetail.sellUnit">/{{ getLabel('sell_unit', serviceDetail.sellUnit) }}</span>
              </div>
              <div v-if="serviceDetail.computeMode==='终端价百分比'">
                <span>{{ serviceDetail.distributePrice }}%</span>
                <span>终端价</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送地区">
            <area-list-view :areas="serviceDetail.region" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业务类型">
            <el-radio-group v-model="addOrChange">
              <el-radio label="add">终端新增配送服务</el-radio>
              <!-- <el-radio label="change">终端更换配送服务</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="添加配送终端"
            prop="selectData"
          >
            <el-select
              v-model="currentSelect"
              style="width: 320px;margin-right: 10px;"
              filterable
              remote
              reserve-keyword
              :remote-method="remoteMethod"
              :loading="proLoading"
              value-key="id"
              placeholder="输入终端名称选择终端"
            >
              <el-option
                v-for="item in terminalOptions"
                :key="item.id"
                :label="item.terminalName"
                :value="item"
              />
            </el-select>
            <el-button
              type="text"
              @click="addItem"
            >添加</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <item-title title="已添加终端列表" />
        </el-col>

        <el-table
          :data="formData.selectData"
          :max-height="400"
          size="small"
          header-cell-class-name="table-header"
          border
        >
          <el-table-column
            prop="terminalName"
            label="终端名称"
            header-align="center"
          />
          <el-table-column
            label="终端所在地区"
            header-align="center"
          >
            <template #default="scope">
              <div>
                <span v-if="scope.row.provinceName">{{ scope.row.provinceName }}</span>
                <span v-if="scope.row.cityName">{{ scope.row.provinceName&&scope.row.cityName?' / ':'' }}{{ scope.row.cityName }}</span>
                <span v-if="scope.row.areaName">{{ scope.row.cityName&&scope.row.areaName?' / ':'' }}{{ scope.row.areaName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="terminalPrice"
            label="终端价（元）"
            header-align="center"
            align="center"
          />
          <el-table-column
            label="营销模式"
            header-align="center"
          >
            <template #default="scope">
              <span v-if="scope.row?.sellMode !== 'direct'">
                {{ scope.row?.agentAttribute === '1' ?'独家招商':'精细招商' }}
              </span>
              <span v-else> 终端直销</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="agentName"
            label="渠道客户名称"
            header-align="center"
          />
          <el-table-column
            prop="distributeName"
            label="已有配送信息"
            header-align="center"
          >
            <template #default="scope">
              <div v-if="scope.row.distributeContractDetails&&scope.row.distributeContractDetails.length">
                <distributors-view
                  :datas="scope.row.distributeContractDetails"
                  :unit="scope.row.sellUnit"
                />
              </div>
              <div v-else>无配送商</div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="text"
                @click="removeItem(scope.$index)"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {defineComponent, getCurrentInstance, inject, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
  name: 'RelevanceTerminal',
  emits: ['onsuccess'],
  setup(props, context) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const formRef = ref(null)
    var reactiveData = reactive({
      proLoading: false,
      addOrChange: 'add',
      serviceDetail: {},
      terminalOptions: [],
      currentSelect: null,
      formData: {
        distributeServeId: 0,
        terminalIds: [],
        selectData: [],
      },
    })
    var formRules = reactive({
      selectData: [
        {
          type: 'array',
          required: true,
          message: '请添加配送终端',
          trigger: 'change',
        },
      ],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const open = (rowData) => {
      reactiveData.serviceDetail = rowData
      reactiveData.formData.distributeServeId = rowData.id
      dialogShow.value = true
    }
    const close = () => {
      reactiveData.currentSelect = null
      formRef.value.resetFields()
      dialogShow.value = false
    }
    const addItem = () => {
      if (!reactiveData.currentSelect) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择要添加的终端',
        })
        return
      }
      const isExit = reactiveData.formData.selectData.findIndex(
        (p) => p.terminalId === reactiveData.currentSelect?.terminalId
      )
      if (isExit === -1) {
        reactiveData.formData.selectData.unshift(reactiveData.currentSelect)
      } else {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '该终端已存在列表中',
        })
      }
      formRef.value.validate()
    }
    const removeItem = (index) => {
      reactiveData.formData.selectData.splice(index, 1)
      formRef.value.validate()
    }
    const remoteMethod = async(query) => {
      if (query !== '') {
        reactiveData.proLoading = true
        var pro = await api.distributors.DISTRIBUTORS_TERMINAL_LIST({
          productId: reactiveData.serviceDetail.productId,
          terminalName: query,
          distributeId: reactiveData.serviceDetail.distributeId,
          region: reactiveData.serviceDetail.region,
        })
        if (pro.code === 0) {
          reactiveData.terminalOptions = pro.data.list
        } else {
          reactiveData.terminalOptions = []
        }
        reactiveData.proLoading = false
      } else {
        reactiveData.terminalOptions = []
      }
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          var subdata = {
            id: reactiveData.formData.distributeServeId,
            devIds: reactiveData.formData.selectData.map((p) => p.id),
          }
          api.distributors
            .DISTRIBUTORS_SERVICE_ADD_TERMINAL(subdata)
            .then((res) => {
              if (res.code === 0) {
                context.emit('onsuccess')
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message:
                    '提交成功，已创建[配送服务关联终端]审批，可在[流程审批-我发起的]查看审批进程',
                })
                close()
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    return {
      formRef,
      ...toRefs(reactiveData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      remoteMethod,
      addItem,
      removeItem,
    }
  },
})
</script>
